#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
为markdown文件生成二级标题目录的脚本
"""

import os
import re
import glob

def extract_h2_titles(content):
    """提取所有二级标题"""
    pattern = r'^##\s+(.+)$'
    matches = re.findall(pattern, content, re.MULTILINE)
    return matches

def create_anchor_link(title):
    """将标题转换为锚点链接"""
    # 移除特殊字符并转换为小写
    anchor = re.sub(r'[^\w\s-]', '', title.lower())
    anchor = re.sub(r'\s+', '-', anchor.strip())
    return f"#{anchor}"

def has_toc(content):
    """检查是否已经存在目录"""
    toc_indicators = [
        '## 📋 目录',
        '## 目录',
        '## Table of Contents',
        '## TOC',
        '## 内容导航'
    ]
    for indicator in toc_indicators:
        if indicator in content:
            return True
    return False

def add_toc_to_file(file_path):
    """为单个文件添加目录"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 检查是否已有目录
        if has_toc(content):
            print(f"跳过: {os.path.basename(file_path)} - 已存在目录")
            return False
        
        # 提取二级标题
        h2_titles = extract_h2_titles(content)
        if len(h2_titles) < 2:
            print(f"跳过: {os.path.basename(file_path)} - 二级标题不足")
            return False
        
        # 创建目录内容
        toc_lines = ['## 📋 目录', '']
        for title in h2_titles:
            anchor = create_anchor_link(title)
            toc_lines.append(f'- [{title}]({anchor})')
        toc_lines.extend(['', '---', ''])
        
        # 找到一级标题后的位置插入目录
        lines = content.split('\n')
        insert_index = 0
        for i, line in enumerate(lines):
            if line.startswith('# ') and not line.startswith('##'):
                insert_index = i + 1
                break
        
        # 插入目录
        new_lines = lines[:insert_index] + toc_lines + lines[insert_index:]
        new_content = '\n'.join(new_lines)
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print(f"成功: {os.path.basename(file_path)} - 添加目录完成")
        return True
        
    except Exception as e:
        print(f"错误: {os.path.basename(file_path)} - {str(e)}")
        return False

def main():
    # 项目根目录
    root_dir = r"e:\BaiduSyncdisk\Android系统开发之路"
    
    # 查找所有markdown文件
    md_files = []
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.md'):
                md_files.append(os.path.join(root, file))
    
    print(f"找到 {len(md_files)} 个markdown文件")
    print("=" * 50)
    
    # 处理每个文件
    success_count = 0
    for file_path in md_files:
        if add_toc_to_file(file_path):
            success_count += 1
    
    print("=" * 50)
    print(f"处理完成: 成功添加 {success_count} 个目录")

if __name__ == "__main__":
    main()